package com.wei.web.exceptionResolver;

import com.wei.utils.exception.ValidatorException;
import com.wei.utils.exception.WorkingException;
import com.wei.web.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ResultVo result = null;
        e.printStackTrace();
        if(e instanceof ValidatorException){//数据检查异常
            ValidatorException validatorException = (ValidatorException)e;
            logger.error("系统校验异常:"+ e.getMessage(),e.getStackTrace());
            result = new ResultVo("500",validatorException.getMessage(),null);
        } else if(e instanceof WorkingException){//业务处理异常
            WorkingException workingException = (WorkingException)e;
            logger.error("系统运行时异常:"+ workingException.getMessage(),workingException.getStackTrace());
            result = new ResultVo("500",workingException.getMessage(),null);
        } else {
            logger.error("系统处理异常:"+ e.getMessage(),e.getStackTrace());
            String message = e.getMessage();
            if(message==null){
                message = e.toString()+"异常";
            }
            result = new ResultVo("500",message,null);
        }
        ModelAndView mv = new ModelAndView();
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        mv.setView(view);
        mv.addObject(result);

        return mv;
    }
}
